package com.cy.pj.sys.service.realm;

import com.cy.pj.sys.dao.CGBInformationDao;
import com.cy.pj.sys.dao.CGBMenuDao;
import com.cy.pj.sys.pojo.CGBInformation;
import com.cy.pj.sys.pojo.CGBMenu;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private CGBMenuDao cgbMenuDao;
    @Autowired
    private CGBInformationDao cgbInformationDao;

    /**获取并封装授权信息*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户
        CGBInformation information=
                (CGBInformation) principalCollection.getPrimaryPrincipal();
        //根据登录用户id，查询用户权限
//        Set<String> permissionSet=
//                cgbMenuDao.selectUserPermissions(information.getId());

//        if(permissionSet==null||permissionSet.isEmpty())
//            throw new AuthorizationException();
        //封装用户权限信息
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
//        info.setStringPermissions(permissionSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo
            (AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取客户端提交的用户名
        UsernamePasswordToken upToken=(UsernamePasswordToken) authenticationToken;
        String username=upToken.getUsername();
        //2.基于用户名查询用户信息
        CGBInformation information=cgbInformationDao.selectUserByUsername(username);
        if(information==null)
            throw new UnknownAccountException();
        //3.封装用户信息
        String realmName=getName();
        SimpleAuthenticationInfo info
                =new SimpleAuthenticationInfo(
                information,
                information.getPassword(),//用户密码
                realmName);
        return info;

    }
}
